package servlet;

import DAO.OrderDAO;
import DAO.ProductImageDAO;
import bean.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.web.util.HtmlUtils;
import util.JSONUtil;
import util.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

public class ForeServlet extends BaseForeServlet {
    public String home(HttpServletRequest request, HttpServletResponse response, Page page) {
        List<Category> categories = (List<Category>) request.getAttribute("categories");
//        System.out.println(categories.size());
        productDAO.fill(categories);
        productDAO.fillByRow(categories);

//        System.out.println(categories.get(5).getProductsByRow().size());
//        request.setAttribute("categories",categories);
        return "home.jsp";
    }

    public String register(HttpServletRequest request, HttpServletResponse response, Page page) {
        request.removeAttribute("msg");
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        if (userDAO.isExist(name)) {
            request.setAttribute("msg", "用户名已存在");
            return "register.jsp";
        }

        User user = new User();
        user.setName(name);
        user.setPassword(pass);
        userDAO.add(user);
        return "success.jsp";

    }

    public String login(HttpServletRequest request, HttpServletResponse response, Page page) {
        request.removeAttribute("msg");
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        User user = userDAO.get(name, pass);
        if (user == null) {
            request.setAttribute("msg", "用户名错误");
            return "login.jsp";
        }
        request.getSession().setAttribute("user", user);
        return "@forehome";
    }

    public String logout(HttpServletRequest request, HttpServletResponse response, Page page) {
        request.getSession().setAttribute("user", null);
        return "login.jsp";
    }

    public String product(HttpServletRequest request, HttpServletResponse response, Page page) {
        int pid = Integer.parseInt(request.getParameter("pid"));
        Product product = productDAO.get(pid);
        productDAO.setSaleAndReviewNumber(product);
        List<ProductImage> images1 = productImageDAO.list(product, ProductImageDAO.type_single);
        List<ProductImage> images2 = productImageDAO.list(product, ProductImageDAO.type_detail);
        List<PropertyValue> values = propertyValueDAO.list(pid);
        List<Review> reviews = reviewDAO.list(pid);
        request.setAttribute("product", product);
        request.setAttribute("values", values);
        request.setAttribute("images1", images1);
        request.setAttribute("images2", images2);
        request.setAttribute("reviews", reviews);
        return "product.jsp";
    }

    public String checkLogin(HttpServletRequest request, HttpServletResponse response, Page page) {
//        System.out.println("1");
        User user = (User) request.getSession().getAttribute("user");
        if (null != user)
            return "%success";
        return "%fail";
    }

    public String loginAjax(HttpServletRequest request, HttpServletResponse response, Page page) {
//        System.out.println("1");
        String name = request.getParameter("name");
        String password = request.getParameter("pass");
        User user = userDAO.get(name, password);

        if (null == user) {
            return "%fail";
        }
        request.getSession().setAttribute("user", user);
        return "%success";
    }

    public String category(HttpServletRequest request, HttpServletResponse response, Page page) {
        int cid = Integer.parseInt(request.getParameter("cid"));
        Category category = categoryDAO.get(cid);
        productDAO.fill(category);
        List<Product> products = productDAO.list(cid);
        productDAO.setSaleAndReviewNumber(products);
        String sort = request.getParameter("sort");
        products = sort(products, sort);
        request.setAttribute("category", category);
        request.setAttribute("products", products);
        return "category.jsp";
    }

    public List<Product> sort(List<Product> products, String sort) {
        Comparator<Product> all = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getName().compareTo(o2.getName());
            }
        };
        Comparator<Product> review = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getReviewCount() - o2.getReviewCount();
            }
        };
        Comparator<Product> newDate = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getCreateDate().compareTo(o2.getCreateDate());
            }
        };
        Comparator<Product> sale = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getSaleCount() - o2.getSaleCount();
            }
        };
        Comparator<Product> price = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                if (o1.getPromotePrice() - o2.getPromotePrice() > 0)
                    return 1;
                else if (o1.getPromotePrice() - o2.getPromotePrice() < 0)
                    return -1;
                return 0;
            }
        };
        Comparator<Product> comparator = null;
        switch (sort) {
            case "all":
                comparator = all;
                break;
            case "review":
                comparator = review;
                break;
            case "newDate":
                comparator = newDate;
                break;
            case "sale":
                comparator = sale;
                break;
            case "price":
                comparator = price;
                break;
        }
        Collections.sort(products, comparator);
        return products;
    }

    public String search(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        String key = request.getParameter("key");
        List<Product> products = productDAO.search(key);
        request.setAttribute("products",products);
        return "search.jsp";
    }

    public String buyOne(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        int num = Integer.parseInt(request.getParameter("num"));
        int pid = Integer.parseInt(request.getParameter("pid"));
        User user = (User) request.getSession().getAttribute("user");
        OrderItem item = new OrderItem();
        item.setSelect(true);
        item.setNumber(num);
        item.setProduct(productDAO.get(pid));
        item.setUser(user);
        orderItemDAO.add(item);
        request.getSession().setAttribute("item",item);

        return "buy.jsp";
    }

    public String addCart(HttpServletRequest request, HttpServletResponse response, Page page) {
        int pid = Integer.parseInt(request.getParameter("pid"));
        int num = Integer.parseInt(request.getParameter("num"));
        User user = (User) request.getSession().getAttribute("user");
        List<OrderItem> items = orderItemDAO.listByUser(user.getId());
        boolean found = false;
        if(null!=items)
        {
            for (OrderItem item:
                    items) {
                if(item.getProduct().getId()==pid)
                {
                    found = true;
                    item.setNumber(num+item.getNumber());
                    orderItemDAO.update(item);
                    break;
                }

            }
        }
        if(!found)
        {
            OrderItem item = new OrderItem();
            item.setNumber(num);
            item.setSelect(false);
            item.setProduct(productDAO.get(pid));
            item.setUser(user);
            orderItemDAO.add(item);
            request.setAttribute("item",item);
        }

        return "%success";
    }

    public String cart(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        User user = (User) request.getSession().getAttribute("user");
        List<OrderItem> items = orderItemDAO.listByUser(user.getId());
        List<OrderItem> newItems =  new ArrayList<>();
        for (int i = 0; i<items.size();i++)
        {
            if(!items.get(i).isSelect())
                newItems.add(items.get(i));
        }
        request.setAttribute("items",newItems);
        return "cart.jsp";
    }

    public String deleteCart(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        User user = (User) request.getSession().getAttribute("user");
        if(null==user)
            return "%fail";
        int oiid = Integer.parseInt(request.getParameter("oiid"));
        orderItemDAO.delete(oiid);
        return "%success";
    }

    public String updateCart(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        User user = (User) request.getSession().getAttribute("user");
        if(null==user)
            return "%fail";
        int oiid = Integer.parseInt(request.getParameter("oiid"));
        int num = Integer.parseInt(request.getParameter("num"));
        OrderItem item = orderItemDAO.get(oiid);
        item.setNumber(num);
        orderItemDAO.update(item);
        return "%success";
    }

    public String order(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        User user = (User) request.getSession().getAttribute("user");
        String sum = request.getParameter("sum");
        JSONObject object = JSONUtil.getJSON(request);
        JSONArray array = JSONArray.fromObject(object.get("sels"));
//        System.out.println(array);
        List<String> selects = (List<String>)array;
//        System.out.println(selects);
        List<OrderItem> items =  orderItemDAO.listByUser(user.getId());
        List<OrderItem> newItems =  new ArrayList<>();
        for (int i = 0; i<items.size();i++)
        {

            items.get(i).setSelect(Boolean.parseBoolean(selects.get(i)));
            if(items.get(i).isSelect())
                newItems.add(items.get(i));
        }
        for (OrderItem item:
             newItems) {
            item.setSelect(false);
//            System.out.println(item.isSelect());
        }
        request.getSession().setAttribute("items1",newItems);
        request.getSession().setAttribute("sum1","￥"+sum);
        return "%";
    }

    public String createOrder(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        User user = (User) request.getSession().getAttribute("user");
        String address = request.getParameter("address");
        String email = request.getParameter("email");
        String myname = request.getParameter("myname");
        String myphone = request.getParameter("myphone");
        String mymsg = request.getParameter("mymsg");
        String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomUtils.nextInt(10000);
        JSONObject object = JSONUtil.getJSON(request);
        JSONArray array = JSONArray.fromObject(object.get("items"));
//        System.out.println(array);
        List<String> ids = (List<String>)array;
        Order order = new Order();
        order.setOrderCode(orderCode);
        order.setStatus(OrderDAO.waitPay);
        order.setAddress(address);
        order.setPost(email);
        order.setReceiver(myname);
        order.setMobile(myphone);
        order.setUser(user);
        order.setUserMessage(mymsg);
        order.setCreateDate(new Date());
        order.setDeliveryDate(null);
        order.setConfirmDate(null);
        order.setPayDate(null);
        orderDAO.add(order);
//        System.out.println(ids);
        for (int i = 0; i < ids.size(); i++) {
            int oiid = Integer.parseInt(ids.get(i));
//            System.out.println(oiid);
            OrderItem item = orderItemDAO.get(oiid);
            item.setSelect(true);
            item.setOrder(order);
            orderItemDAO.update(item);
        }
            orderItemDAO.fill(order);
//
//        for (int i = 0; i <items.length ; i++) {
//            OrderItem item = orderItemDAO.get(items[i]);
//            item.setOrder(order);
//        }

//
        request.getSession().setAttribute("myorder",order);
        return "%pay.jsp";
    }

    public String pay(HttpServletRequest request, HttpServletResponse response, Page page){
        int oid = Integer.parseInt(request.getParameter("oid"));
        Order order = orderDAO.get(oid);
        orderItemDAO.fill(order);
        request.getSession().setAttribute("myorder",order);
        return "pay.jsp";
    }

    public String delivery(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        int oid = Integer.parseInt(request.getParameter("oid"));
        Order order = orderDAO.get(oid);
        orderItemDAO.fill(order);
        order.setPayDate(new Date());
        order.setStatus(OrderDAO.waitDelivery);
        orderDAO.update(order);
        request.setAttribute("order",order);
        return "delivery.jsp";
    }
    public String confirm(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        int oid = Integer.parseInt(request.getParameter("oid"));
        Order order = orderDAO.get(oid);
        orderItemDAO.fill(order);
        order.setStatus(OrderDAO.waitConfirm);
        orderDAO.update(order);
        request.setAttribute("order",order);
        return "confirm.jsp";
    }

    public String finish(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        int oid = Integer.parseInt(request.getParameter("oid"));
        Order order = orderDAO.get(oid);
        orderItemDAO.fill(order);
        order.setConfirmDate(new Date());
        order.setStatus(OrderDAO.waitReview);
        orderDAO.update(order);
        return "finish.jsp";
    }

    public String orderlist(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        User user = (User) request.getSession().getAttribute("user");
        String status = request.getParameter("status");
        List<Order> orders;
        if(null==status)
        {
            orders = orderDAO.list(user.getId());
        }
        else
         orders = orderDAO.list(user.getId(),status);
        for (Order o:
             orders) {
            orderItemDAO.fill(o);
            for (OrderItem item:
                 o.getOrderItems()) {
            }
        }
        request.setAttribute("orders",orders);
        request.setAttribute("status",status);
        return "orderList.jsp";
    }

    public String deleteOrder(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        int oid = Integer.parseInt(request.getParameter("oid"));
        Order o = orderDAO.get(oid);
        o.setStatus(OrderDAO.delete);
        orderDAO.update(o);
        return "@foreorderlist";
    }

    public String access(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        int oiid = Integer.parseInt(request.getParameter("oiid"));
        OrderItem item = orderItemDAO.get(oiid);
        Product product = item.getProduct();
        productDAO.setSaleAndReviewNumber(product);
        request.setAttribute("item",item);
        return "access.jsp";
    }

    public String review(HttpServletRequest request, HttpServletResponse response, Page page)
    {
        int oiid = Integer.parseInt(request.getParameter("oiid"));
        String content = request.getParameter("content");
        content = HtmlUtils.htmlEscape(content);
        User user = (User)request.getSession().getAttribute("user");
        OrderItem item = orderItemDAO.get(oiid);
        Product product = item.getProduct();
        productDAO.setSaleAndReviewNumber(product);
        Order order = item.getOrder();
        order.setStatus(OrderDAO.finish);
        orderDAO.update(order);
        Review review = new Review();
        review.setContent(content);
        review.setProduct(item.getProduct());
        review.setUser(user);
        review.setCreateDate(new Date());
        reviewDAO.add(review);
        List<Review> reviews = reviewDAO.list(item.getProduct().getId());
        request.setAttribute("item",item);
        request.setAttribute("reviews",reviews);
        return "review.jsp";
    }


}
